package com.ruoyi.cm.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.base.domain.BaseBsBd;
import com.ruoyi.base.domain.BaseBsProject;
import com.ruoyi.base.mapper.BaseBsBdMapper;
import com.ruoyi.base.mapper.BaseBsProjectMapper;
import com.ruoyi.base.service.IBaseBsBdService;
import com.ruoyi.base.service.IBaseBsProjectService;
import com.ruoyi.cm.domain.CmBsQs;
import com.ruoyi.cm.domain.CmReport;
import com.ruoyi.cm.domain.vo.ReportVo;
import com.ruoyi.cm.mapper.CmBsQsMapper;
import com.ruoyi.cm.mapper.CmReportMapper;
import com.ruoyi.common.utils.BigDecimalUtil;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckLogin;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.cm.domain.vo.CmBdQsCountVo;
import com.ruoyi.cm.domain.bo.CmBdQsCountBo;
import com.ruoyi.cm.service.ICmBdQsCountService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 标段期数计算
 *
 * @author zxs
 * @date 2024-09-30
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/cm/bdQsCount")
public class CmBdQsCountController extends BaseController {

    private final ICmBdQsCountService iCmBdQsCountService;
    private final IBaseBsBdService bdService;
    private final IBaseBsProjectService projectService;
    private final BaseBsBdMapper bdMapper;
    private final BaseBsProjectMapper projectMapper;
    private final CmBsQsMapper qsMapper;
    private final CmReportMapper reportMapper;
    private final TaskService taskService;


    /**
     * 查询标段期数计算列表
     */
    @SaCheckLogin
    @GetMapping("/list")
    public TableDataInfo<CmBdQsCountVo> list(CmBdQsCountBo bo, PageQuery pageQuery) {
        return iCmBdQsCountService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出标段期数计算列表
     */
    @SaCheckLogin
    @Log(title = "标段期数计算", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(CmBdQsCountBo bo, HttpServletResponse response) {
        List<CmBdQsCountVo> list = iCmBdQsCountService.queryList(bo);
        ExcelUtil.exportExcel(list, "标段期数计算", CmBdQsCountVo.class, response);
    }

    /**
     * 获取标段期数计算详细信息
     *
     * @param id 主键
     */
    @SaCheckLogin
    @GetMapping("/{id}")
    public R<CmBdQsCountVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iCmBdQsCountService.queryById(id));
    }

    /**
     * 获取开票汇总列表信息
     *
     * @param bo
     */
    @SaCheckLogin
    @GetMapping("/getInvoiceSummary")
    public R<List<CmBdQsCountVo>> getInvoiceSummary(CmBdQsCountBo bo) {
        return R.ok(iCmBdQsCountService.getInvoiceSummary(bo));
    }

    /**
     * 获取报表管理信息
     *
     * @param bo
     */
    @SaCheckLogin
    @GetMapping("/getReportInfo")
    public R<List<ReportVo>> getReportInfo(CmBdQsCountBo bo) {
        return R.ok(iCmBdQsCountService.getReportInfo(bo));
    }


    /**
     * 获取标段所有站点的支付统计列表信息
     *
     * @param bo
     */
    @SaCheckLogin
    @GetMapping("/getPaymentList")
    public R<Map<String,List<Map<String,String>>>> getPaymentList(CmBdQsCountBo bo) {
        return R.ok(iCmBdQsCountService.getPaymentList(bo));
    }


    /**
     * 导出报表数据
     */
    @PostMapping("/exportReport")
    public void exportReport(HttpServletResponse response, CmBdQsCountBo bo) {
        List<ReportVo> list = iCmBdQsCountService.getReportInfo(bo);
        if(CollUtil.isEmpty(list)){
            return;
        }
        // 标题部分
        Long bdId = bo.getBdId();
        Long qsId = bo.getQsId();
        String deptName = "";
        String projectName = "";
        String bdName = "";
        String qsName = "";
        String cbDeptName = "";
        String jlDeptName = "";
        String jiezrq = "";

        BaseBsBd bd = bdMapper.selectById(bdId);
        bdName = bd.getName();
        cbDeptName = bd.getSgdwName();
        jlDeptName = bd.getJldwName();
        Long projectId = bd.getProjectId();
        projectName = bd.getProjectName();
        BaseBsProject project = projectMapper.selectById(projectId);
        deptName = project.getDeptName();
        CmBsQs qs = qsMapper.selectById(qsId);
        qsName = qs.getSettleName();

        // 报表数据
        LambdaQueryWrapper<CmReport> lqw = Wrappers.lambdaQuery();
        lqw.eq(qsId != null, CmReport::getQsId, qsId);
        lqw.eq(bdId != null, CmReport::getBdId, bdId);
        List<CmReport> reportList = reportMapper.selectList(lqw);
        CmReport report = reportList.get(0);
        if (report != null && report.getProcInsId() != null) {
            Task task = taskService.createTaskQuery().processInstanceId(report.getProcInsId()).singleResult();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            jiezrq = sdf.format(task.getCreateTime());
        }

//        int i = 1;
        //加序号，行末合计；
        ReportVo last = new ReportVo();
        BigDecimal danzdzj = BigDecimal.ZERO;
        BigDecimal yzfyfk = BigDecimal.ZERO;
        BigDecimal ljkcyfk = BigDecimal.ZERO;
        BigDecimal bckk = BigDecimal.ZERO;
        BigDecimal ljkk = BigDecimal.ZERO;
        BigDecimal jzscljfk = BigDecimal.ZERO;
        BigDecimal bcfk = BigDecimal.ZERO;
        BigDecimal jzbcljfk = BigDecimal.ZERO;

        for(int i=0; i<list.size(); i++) {
            ReportVo vo = list.get(i);
            vo.setXuh(i+1);
            if(vo.getDanzdzj()!=null){
                danzdzj = BigDecimalUtil.add(danzdzj,vo.getDanzdzj());
            }
            if(vo.getYizfyfk()!=null){
                yzfyfk = BigDecimalUtil.add(yzfyfk,vo.getYizfyfk());
            }
            if(vo.getLeijkcyfk()!=null){
                ljkcyfk = BigDecimalUtil.add(ljkcyfk,vo.getLeijkcyfk());
            }
            if(vo.getBenckkje()!=null){
                bckk = BigDecimalUtil.add(bckk,vo.getBenckkje());
            }
            if(vo.getLeijkkje()!=null){
                ljkk = BigDecimalUtil.add(ljkk,vo.getLeijkkje());
            }
            if(vo.getJiezscljfkje()!=null){
                jzscljfk = BigDecimalUtil.add(jzscljfk,vo.getJiezscljfkje());
            }
            if(vo.getBencfkje()!=null){
                bcfk = BigDecimalUtil.add(bcfk,vo.getBencfkje());
            }
            if(vo.getJiezbcljfkje()!=null){
                jzbcljfk = BigDecimalUtil.add(jzbcljfk,vo.getJiezbcljfkje());
            }
        }
        last.setName("合计");
        last.setDanzdzj(danzdzj);
        last.setYizfyfk(yzfyfk);
        last.setLeijkcyfk(ljkcyfk);
        last.setBenckkje(bckk);
        last.setLeijkkje(ljkk);
        last.setJiezscljfkje(jzscljfk);
        last.setBencfkje(bcfk);
        last.setJiezbcljfkje(jzbcljfk);
        list.add(last);
        Map<String, String> map = new HashMap<>();
        map.put("deptName", deptName);
        map.put("projectName", projectName);
        map.put("bdName", bdName);
        map.put("qsName", qsName);
        map.put("cbDeptName", cbDeptName);
        map.put("jlDeptName", jlDeptName);
        map.put("jiezrq", jiezrq);
        ExcelUtil.exportTemplate(CollUtil.newArrayList(map, list), "报表管理.xlsx", "excel/报表管理.xlsx", response);
    }

    /**
     * 导出开票汇总数据
     */
    @PostMapping("/exportInvoiceSummary")
    public void exportInvoiceSummary(HttpServletResponse response, CmBdQsCountBo bo) {
        List<CmBdQsCountVo> list = iCmBdQsCountService.getInvoiceSummary(bo);
        if(CollUtil.isEmpty(list)){
            return;
        }
        int i = 1;
        //加序号及行末合计；
        CmBdQsCountVo last = new CmBdQsCountVo();
        BigDecimal diyckp = BigDecimal.ZERO;
        BigDecimal bckp = BigDecimal.ZERO;
        BigDecimal bczf = BigDecimal.ZERO;
        BigDecimal yzf = BigDecimal.ZERO;
        BigDecimal ljzf = BigDecimal.ZERO;
        BigDecimal dkp = BigDecimal.ZERO;
        for(CmBdQsCountVo vo : list){
            vo.setXuh(i++);
            if(vo.getDyckpje()!=null){
                diyckp = BigDecimalUtil.add(diyckp,vo.getDyckpje());
            }
            if(vo.getBckpje()!=null){
                bckp = BigDecimalUtil.add(bckp,vo.getBckpje());
            }
            if(vo.getBqzfje()!=null){
                bczf = BigDecimalUtil.add(bczf,vo.getBqzfje());
            }
            if(vo.getYzfje()!=null){
                yzf = BigDecimalUtil.add(yzf,vo.getYzfje());
            }
            if(vo.getLjzfje()!=null){
                ljzf = BigDecimalUtil.add(ljzf,vo.getLjzfje());
            }
            if(vo.getDkpje()!=null){
                dkp = BigDecimalUtil.add(dkp,vo.getDkpje());
            }
        }
        last.setZdName("合计");
        last.setDyckpje(diyckp);
        last.setBckpje(bckp);
        last.setBqzfje(bczf);
        last.setYzfje(yzf);
        last.setLjzfje(ljzf);
        last.setDkpje(dkp);
        list.add(last);
        //查询标段名称和期数；
        Map<String, String> map = new HashMap<>();
//        map.put("",)
        ExcelUtil.exportTemplate(CollUtil.newArrayList(map, list), "开票汇总.xlsx", "excel/开票汇总.xlsx", response);
    }


    /**
     * 新增标段期数计算
     */
    @SaCheckLogin
    @Log(title = "标段期数计算", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody CmBdQsCountBo bo) {
        return toAjax(iCmBdQsCountService.insertByBo(bo));
    }

    /**
     * 修改标段期数计算
     */
    @SaCheckLogin
    @Log(title = "标段期数计算", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody CmBdQsCountBo bo) {
        return toAjax(iCmBdQsCountService.update(bo));
    }

    /**
     * 删除标段期数计算
     *
     * @param ids 主键串
     */
    @SaCheckLogin
    @Log(title = "标段期数计算", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iCmBdQsCountService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
